<template>
  <div class="scrollable-form">
    <div class="form-wrapper">
      <el-form
        ref="ruleForm"
        :rules="rules"
        :model="formData"
        label-position="left"
        label-width="80px"
        size="medium"
        v-loading="loading"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="中文名"
              :label-width="width"
              class="form-item"
              prop="wzm"
            >
              <el-input v-model="formData.wzm" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="拉丁名" :label-width="width" class="form-item" prop="ldm">
              <el-input v-model="formData.ldm" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="观测者" :label-width="width" class="form-item">
              <el-input v-model="formData.guance" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="实体数量"
              :label-width="width"
              class="form-item"
              prop="shitishuliang"
            >
              <el-input v-model.number="formData.shitishuliang" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="痕迹种类及数量"
              :label-width="width"
              class="form-item"
              prop="henjishuliang"
            >
              <el-input v-model.number="formData.henjishuliang" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经度" :label-width="width" class="form-item" prop="jd">
              <el-input v-model="formData.jd" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="纬度" :label-width="width" class="form-item" prop="wd">
              <el-input v-model="formData.wd" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="海拔" :label-width="width" class="form-item" >
              <el-input v-model="formData.hb" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="坡度" :label-width="width" class="form-item">
              <el-input v-model="formData.podu" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="坡位" :label-width="width" class="form-item">
              <el-input v-model="formData.powei" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="坡向" :label-width="width" class="form-item">
              <el-input v-model="formData.poxiang" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="栖息地类型"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.qixi" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="调查日期及发现时间"
              :label-width="width"
              class="form-item"
            >
              <el-date-picker
                v-model="formData.diaochariqi"
                type="datetime"
                placeholder="选择日期和时间"
                style="width: 100%"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="栖息地干扰"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.qixiganrao" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="保护等级"
              :label-width="width"
              class="form-item"
            >
              <el-select
                v-model="formData.protectlevel"
                placeholder="请选择"
                style="width: 100%"
                @change="handleOptionChange1"
              >
                <el-option
                  v-for="list in list1"
                  :key="list.value"
                  :label="list.label"
                  :value="list.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="发现地址"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.location" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盟市" :label-width="width" class="form-item">
              <el-input v-model="formData.mengshi" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="旗县" :label-width="width" class="form-item">
              <el-input v-model="formData.qixian" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="数据来源"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.source" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="this.pageTitle=='新增数据'">
            <el-form-item
              label="动物分类"
              :label-width="width"
              class="form-item"
              prop="category"
            >
            <el-select v-model="formData.category" @change="handleOptionChange" placeholder="请选择">
    <el-option
      v-for="item in categoryOptions"
      :key="item.key"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
            </el-form-item>
            
          </el-col>
        </el-row>

        <!-- 特征描述单独一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="特征描述"
              :label-width="width"
              class="form-item"
            >
              <el-input
                v-model="formData.tezhengmiaoshu"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 分布多度描述单独一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="分布多度描述"
              :label-width="width"
              class="form-item"
            >
              <el-input
                v-model="formData.fenbuduodumiaoshu"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
        <el-col :span="24">
          <!-- 在这里添加上传图片 -->
          <el-form-item label="物种照片"  :label-width="width"
              class="form-item">
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="actionUrl"
              :data="{ ydbh: formData.id }"
              :on-success="handleUploadSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :before-upload="beforeFileUpload"
              list-type="picture-card"
              
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
         <el-row>
        <el-col :span="24">
          <!-- 在这里添加上传图片 -->
          <el-form-item label="生境照片"  :label-width="width"
              class="form-item">
            <el-upload
              ref="uploadHabitat"
              class="upload-demo"
              :action="actionUrl"
              :data="{ ydbh: formData.id }"
              :on-success="handleUploadSuccess1"
              :on-preview="handlePictureCardPreview1"
              :on-remove="handleRemove1"
              :file-list="fileList1"
              :before-upload="beforeFileUpload"
              list-type="picture-card"
              
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible1">
              <img width="100%" :src="dialogImageUrl1" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      </el-form>
    </div>
    <div class="btn" style="text-align: center">
      <el-button style="margin-right: 8px" @click="goBack">返回</el-button>
      <el-button
        type="danger"
        style="background-color: #1890ff; border-color: #1890ff"
         @click="onSubmit('ruleForm')"
        >{{ this.pageTitle }}</el-button
      >
    </div>
  </div>
</template>

<script>
import commonOper from "../../../../utils/commonOper";
import config from "@/config/config.js";
import { getToken } from '@/utils/auth' ;
export default {
  name: "MammalAdd",
  data() {
    return {
      pageTitle: "新增数据",
      width: "140px",
      isFormValid: false,
      isDataLoaded: false,
      
      formData: {
        id:"",
        wzm: null,
        ldm: null,
        shitishuliang: '',
        henjishuliang: '',
        jd: '',
        wd: '',
        hb: '',
        id: null,
        podu: null,
        powei: null,
        poxiang: null,
        qixi: null,
        diaochariqi: null,
        qixiganrao: null,
        protectlevel: null,
        location: null,
        mengshi: null,
        qixian: null,
        source: null,
        guance: null,
        zpbh: null,
        sjzpbh: null,
        tezhengmiaoshu: null,
        fenbuduodumiaoshu: null,
        category: "",
      },
      plantList: [],
      categoryOptions:[{key: 2, label: "哺乳动物", value: "01"},
      {key: 3, label: "鸟类", value: "02"},{key: 4, label: "鱼类", value: "03"},{key: 5, label: "节肢动物", value: "04"}],
      list1: [
        { label: "一级", value: "01" },
        { label: "二级", value: "02" },
        { label: "未列入", value: "03" },
      ],
      rules: {
          wzm: [
            { required: true, message: '请输入中文名', trigger: 'blur' }
          ],
          ldm: [
            { required: true, message: '请输入学名', trigger: 'blur' }
          ],
          shitishuliang: [
            { required: false, message: '请输入实体数量', trigger: 'blur' },
            { type: 'number', message: '实体数量必须为数字值'}
          ],
          henjishuliang: [
            { required: false, message: '请输入实体数量', trigger: 'blur' },
            { type: 'number', message: '痕迹种类及数量必须为数字值'}
          ],
          jd: [
            { required: true, message: '请输入经度', trigger: 'blur' }
          ],
          wd: [
             { required: true, message: '请输入纬度', trigger: 'blur' }
          ],
          category: [
            { required: true, message: '请选择动物分类', trigger: 'change' }
          ],
      },
      loading:false,
      actionUrl:config.webapiUrl+"rest//uploadpic",
       dialogImageUrl: "",
      dialogImageUrl1: "",
      dialogVisible: false,
      dialogVisible1: false,
      // imageNames: [], // 用于存储上传的图片名字
      fileList: [], // 添加这个数据用于存储上传的文件列表
      fileList1: [], // 添加这个数据用于存储上传的文件列表
    };
  },
  mounted() {
    if (!this.$route.query.data) {
      this.pageTitle = '新增数据';
    } else {
      const data = JSON.parse(this.$route.query.data);
      this.formData = data;
      this.pageTitle = "修改数据";
      let baseURL = "http://49.232.236.127/wzimg/";
            let pathsArray = [];
            let pathsArray1 = [];

            if(data.zpbh!=null&&data.zpbh.length>0){
              var photoArr = data.zpbh.split(",");// 使用 trim() 移除可能存在的空格
              photoArr.forEach(function(photo) {
              pathsArray.push({name:photo,url:baseURL+photo});
            });
            }
          this.fileList=pathsArray;

          if(data.sjzpbh!=null&&data.sjzpbh.length>0){
              var photoArr = data.sjzpbh.split(",");// 使用 trim() 移除可能存在的空格
              photoArr.forEach(function(photo) {
              pathsArray1.push({name:photo,url:baseURL+photo});
            });
            }
            this.fileList1=pathsArray1;
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    handleOptionChange(val){
      this.formData.category=val;
    },
    onSubmit(formName) {
     
      let that = this;
      let surl='';
      let isSubmit=false;
      this.$refs[formName].validate((valid) => {
          if (valid) {
            isSubmit=true;
          }
      });
      //处理照片
      
      let pthtostr="";
      this.fileList.forEach(function(item) {
        if(item.response!=undefined){
           pthtostr+=item.response.data.newFileName+",";
        }else{
           pthtostr+=item.name+",";
        } 
      });
      this.formData.zpbh=pthtostr.slice(0, -1);

      let pthtostr1="";
      this.fileList1.forEach(function(item) {
        if(item.response!=undefined){
           pthtostr1+=item.response.data.newFileName+",";
        }else{
           pthtostr1+=item.name+",";
        } 
      });
      this.formData.sjzpbh=pthtostr1.slice(0, -1);

      if(!isSubmit){
        this.$message.error('数据校验错误，请检查数据内容是否符合要求！');
        return;
      }

      if (this.pageTitle === "新增数据") {
        surl=config.webapiUrl+"nd/animalsurvey/addSurveyPoint";
      } else if (this.pageTitle === "修改数据") {
        surl=config.webapiUrl+"/nd/animalsurvey/editSurveyPoint";

      }
      that.loading = true;
      let paramscommo = {
        this: that,
        url: surl,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        data: that.formData,
        successFunc: function (response) {
          that.loading = false;
          if (response.data.code == 0) {
            that.$message.success("保存成功！");
             // 延迟一下再返回，让用户看到成功提示
            setTimeout(() => {
              this.goBack();
            }, 1000);
          } else {
            let params = {
              this: that,
              title: "提示",
              message: "保存失败，请稍后重试！" + response.data.msg,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          }
        },
        failFunc: function (response) {
          that.loading = false;
          let params = {
            this: that,
            title: "提示",
            message: "网络异常，请稍后重试！" + response.data.data,
            successFunc: function () {},
          };
          commonOper.showWarnAlert(params);
        },
      };
      commonOper.HttpPost(paramscommo);
    },
     beforeFileUpload(file){
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 50;

        if (!isJpgOrPng) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 50MB!');
        }
        return isJpgOrPng && isLt2M;
    },
    handleRemove(file, fileList) {
      // 处理文件删除逻辑
      this.fileList=fileList;
    },
    handleRemove1(file, fileList) {
      // 处理文件删除逻辑
      this.fileList1=fileList;
    },

    handleUploadSuccess(response, file, fileList) {
      
      if (response.code == -1) {
        this.$message.error(response.msg);
        // 删除重复的文件
        // console.log("delete before:",this.fileList);
        // const index = this.fileList.findIndex(
        //   (item) => item.name === file.name
        // );
        // console.log("index:",index);
        // if (index !== -1) {
        //   this.fileList.splice(index, 1);
        // }
        // console.log("delete after:",this.fileList);
        return;
      }
      this.fileList=fileList;
      this.$message.success("物种图片上传成功");
     
    },

    handleUploadSuccess1(response, file, fileList) {
      
      if (response.code == -1) {
        this.$message.error(response.msg);
        // 删除重复的文件
        // console.log("delete before:",this.fileList);
        // const index = this.fileList.findIndex(
        //   (item) => item.name === file.name
        // );
        // console.log("index:",index);
        // if (index !== -1) {
        //   this.fileList.splice(index, 1);
        // }
        // console.log("delete after:",this.fileList);
        return;
      }
      this.fileList1=fileList;
      this.$message.success("物种图片上传成功");
     
    },
    // 预览图片
    handlePictureCardPreview(file) {
     
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreview1(file) {
     
      this.dialogImageUrl1 = file.url;
      this.dialogVisible1 = true;
    },
    handleOptionChange1() {
      switch (this.formData.protectlevel) {
        case "一级":
          this.formData.protectlevel = "一级";
          break;
        case "二级":
          this.formData.protectlevel = "二级";
          break;
        case "未列入":
          this.formData.protectlevel = "未列入";
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style scoped>
.scrollable-form {
  display: flex;
  flex-direction: column;
  height: 90vh;
}
.form-wrapper {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ccc;
  padding: 20px;
  border-bottom: none;
}
.form-item {
  border: 1px solid #ccc;
  padding: 10px;
  background-color: #fafafa;
}
.label {
  font-weight: bold;
  text-align: left;
}
.el-input {
  width: 100%;
}
.btn {
  padding: 20px;
  border-top: 1px solid #ccc;
  position: sticky;
  bottom: 0;
  background-color: #fff;
}
.jdt {
  overflow: hidden;
  display: inline-block;
  width: 100%;
  text-align: start;
  vertical-align: top;
  margin: 0;
  padding: 0;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5;
  list-style: none;
  font-feature-settings: "tnum";
  position: relative;
  display: table;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>
